<template>
  <view
    style="
      width: 100%;
      height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    "
  >
    <view style="padding: 0 20rpx">
      <view class="cell">
        <view class="cell-item" style="width: 100%">
          <text>条码:</text>
          <input type="text" :disabled="true" v-model="tm" />
        </view>
      </view>
      <view class="cell">
        <view class="cell-item">
          <text>货号:</text>
          <input type="text" :disabled="true" v-model="bbreed" />
        </view>
        <view class="cell-item">
          <text>颜色:</text>
          <input type="text" :disabled="true" v-model="color" />
        </view>
      </view>
      <view class="cell">
        <view class="cell-item">
          <text>尺码:</text>
          <input type="text" :disabled="true" v-model="chima" />
        </view>
        <view class="cell-item">
          <text>数量:</text>
          <input type="number" :disabled="true" v-model="sl" />
        </view>
      </view>
      <view
        style="
          margin: auto;
          width: 96%;
          display: flex;
          justify-content: space-between;
        "
      >
        <button
          size="mini"
          type="primary"
          style="color: #fff; width: 48%; height: 80rpx; line-height: 80rpx"
          @tap="del"
        >
          清除
        </button>
        <button
          size="mini"
          type="primary"
          :disabled="saveFlag"
          style="color: #fff; width: 48%; height: 80rpx; line-height: 80rpx"
          @tap="save"
        >
          确定
        </button>
      </view>
    </view>
    <view class="btminfo" style="overflow: auto; flex: 1">
      <t-table style="width: 100%; z-index: 10">
        <t-tr>
          <t-td style="flex: 0 0 120upx; word-break: break-word">货号</t-td>
          <t-td style="flex: 0 0 120upx; word-break: break-word">颜色</t-td>
          <t-td style="flex: 0 0 120upx; word-break: break-word">尺码</t-td>
          <t-td style="flex: 0 0 100upx; word-break: break-word">数量</t-td>
          <t-td style="flex: 1; word-break: break-word">条码</t-td>
        </t-tr>
        <t-tr v-for="(item, index) in arr" :key="item.barcode">
          <t-td style="flex: 0 0 120upx; word-break: break-word">{{
            item.bbreed
          }}</t-td>
          <t-td style="flex: 0 0 120upx; word-break: break-word">{{
            item.color
          }}</t-td>
          <t-td style="flex: 0 0 120upx; word-break: break-word">{{
            item.chima
          }}</t-td>
          <t-td style="flex: 0 0 100upx; word-break: break-word">{{
            item.sl
          }}</t-td>
          <t-td style="flex: 1; word-break: break-word">{{
            item.barcode
          }}</t-td>
        </t-tr>
      </t-table>
    </view>
    <view style="height: 100rpx; border-top: 1px solid #ccc">
      <view
        style="
          text-align: center;
          color: #f0301f;
          font-size: 40upx;
          margin-left: 20rpx;
        "
      >
        已扫描{{ sum }}个条码
      </view>
      <!-- <view style="width: 50%;display: flex;align-items: center;">
				<button size="mini" type="primary"  style="color: #fff;width: 80%;height: 80rpx;line-height: 80rpx;" @tap="save">打印</button>
			</view> -->
    </view>
    <scanCode></scanCode>
    <kk-printer
      style="position: fixed; left: 10000px"
      ref="kkprinter"
      :bufferData="bufferData"
    ></kk-printer>
  </view>
</template>

<script>
import scanCode from "@/static/scan-code/scan-code.vue";
// import Voice from '@/static/voice.js'; //语音文件
import axios from "@/static/axios.js";
import tTable from "@/static/t-table/t-table.vue";
import tTh from "@/static/t-table/t-th.vue";
import tTr from "@/static/t-table/t-tr.vue";
import tTd from "@/static/t-table/t-td.vue";
const TTSSpeech = uni.requireNativePlugin("MT-TTS-Speech");
import * as blesdk from "@/components/kk-printer/utils/bluetoolth.js";
import kkPrinter from "@/components/kk-printer/index.vue";
var app = getApp();
import tsc from "@/utils/tsc.js";
export default {
  components: {
    kkPrinter,
    scanCode,
    tTable,
    tTh,
    tTr,
    tTd,
  },
  data() {
    return {
      tm: "",
      num: 0,
      arr: [],
      sl: "",
      color: "",
      chima: "",
      bbreed: "",
      url: "",
      chuanghao: "",
      jhh: "",
      jhhArr: [],
      uid: "",
      uname: "",
      temp: [],
      isShow: true,
      saveFlag: false,
      bufferData: "",
      sucBackData: [],

	  // 打印
      looptime: 0,
      currentTime: 1,
      lastData: 0,
      oneTimeData: 0,
      buffSize: [],
      buffIndex: 0,
      printNum: [],
      printNumIndex: 0,
      printerNum: 1,
      currentPrint: 1,
      isLabelSend: false,
      isQuery: false,
      canvasWidth: 100,
      canvasHeight: 100,
      jpgWidth: 200,
      jpgHeight: 200,
      role: "",
      roleList: {},
      btnFlag: false,
      printArr: [],
      title: "",
      ids: "",
      ok_printer_sn: "",
      ydytitle: "",
      pz: 0,
      projectName: "",
	  deviceId: '',
    };
  },
  onLoad() {

	this.deviceId = app.globalData.BLEInformation.deviceId
    this.url =
      uni.getStorageSync("url") == ""
        ? this.websiteUrl
        : uni.getStorageSync("url");
    this.uid = uni.getStorageSync("uid");
    this.uname = uni.getStorageSync("uname");
    TTSSpeech.init((status) => {
      if (status === 0) {
        // console.log('引擎初始化成功')
      }
    }, "com.iflytek.speechcloud");
    var _this = this;
    uni.$off("scancodedate");
    uni.$on("scancodedate", function (content) {
      // if (_this.tm != content) {
      console.log(content, "content");
      if (_this.arr.some((item) => item.barcode == content)) {
        uni.showToast({
          title: "此条码已扫描!",
          icon: "none",
          duration: 3000,
        });
        TTSSpeech.speak({
          text: "此条码已扫描",
        });
        return;
      }
      uni.request({
        url: `http://${_this.url}/bService.asmx/GetCpBarcode`,
        method: "GET",
        dataType: "json",
        data: {
          barcode: content,
          huohao: _this.arr.length > 0 ? _this.arr[0].huohao : "",
        },
        success: (r) => {
          console.log(r);
          if (r.data.code == 200) {

            let temp = r.data.data[0];
            _this.tm = temp.barcode;
            _this.sl = temp.sl;
            _this.bbreed = temp.bbreed;
            _this.color = temp.color;
            _this.chima = temp.chima;
            _this.arr.push({
              bbreed: temp.bbreed,
              color: temp.color,
              chima: temp.chima,
              sl: temp.sl,
              barcode: temp.barcode,
            });
          }

          uni.showToast({
            title: r.data.msg,
            icon: "none",
            duration: 3000,
          });
          TTSSpeech.speak({
            text: r.data.msg,
          });
        },
        complete: (r) => {
          console.log(r.statusCode != 200);
          if (r.statusCode != 200) {
            uni.showToast({
              title: "网络请求失败!",
              icon: "none",
              duration: 3000,
            });
          }
        },
      });
    });
  },
  onReady() { // 打印使用
    var list = [];
    var numList = [];
    var j = 0;

    for (var i = 20; i < 200; i += 10) {
      list[j] = i;
      j++;
    }

    for (var i = 1; i < 10; i++) {
      numList[i - 1] = i;
    }

    this.setData({
      buffSize: list,
      oneTimeData: list[0],
      printNum: numList,
      printerNum: numList[0],
    });
  },
  computed: {
    sum() {
      return this.arr.length;
    },
  },
  methods: {
    saveInfo() {
      if (!this.tm) {
        uni.showToast({
          title: "请先扫条码",
          icon: "none",
          duration: 3000,
        });
        TTSSpeech.speak({
          text: "请先扫条码",
        });
        return;
      }
      this.arr = this.arr.concat(this.temp);
      this.temp = [];
      this.tm = "";
      this.sl = "";
    },
    del() {
      if (this.arr.length == 0) {
        uni.showToast({
          title: "请先扫条码",
          icon: "none",
          duration: 3000,
        });
        TTSSpeech.speak({
          text: "请先扫条码",
        });
        return;
      }
      var _this = this;
      uni.showModal({
        title: "提示",
        content: "是否删除最后一行数据",
        success: function (res) {
          if (res.confirm) {
            _this.arr.pop();
            TTSSpeech.speak({
              text: "删除成功",
            });
          }
        },
      });
    },
    padStringsToMaxLength(str, maxLength) {
      // 第一步：将字符串分割成数组，并去除每个元素两端的空格
      let items = str.split(",").map((item) => item.trim());
      // 第二步：找到数组中最长的字符串长度
      let paddedItems = items.map((item) => item.padEnd(maxLength, " "));
      // 第四步：将处理后的数组元素用逗号和一个空格连接起来
      let resultStr = paddedItems.join(",");
      return resultStr;
    },
    printSingleItem(index) {
		var _this = this
		var command = tsc.jpPrinter.createNew();
		command.setCls();
		command.setSize(80, 70);
		command.setGap(0);
		command.setCls();
		command.setBox(20, 20, 600, 520, 1); //绘制一个边框
		command.setText(30, 30, "TSS24.BF2", 0, 2, 2, `货号 ${_this.sucBackData[index].huohao}`);
		command.setText(30, 80, "TSS24.BF2", 0, 2, 2, `颜色 ${_this.sucBackData[index].color}`);

		command.setText(30, 150, "TSS24.BF2", 0, 2, 2, `尺码`);

		command.setText(145, 130, "TSS24.BF2", 0, 2, 2, _this.sucBackData[index].strChima);
		command.setText(145, 180, "TSS24.BF2", 0, 2, 2, _this.sucBackData[index].strSl);

		command.setBarCode(90, 410, "128M", 70, 1, 0, 2, 4, _this.sucBackData[index].barcode); // 绘制条码
		command.setPagePrint(); //执行打印指令
		this.setData({
			isLabelSend: true,
		});
		console.log(command.getData());
		setTimeout(() => {
			this.prepareSend(command.getData());
		}, 500);
    },
    save() {
      if (this.arr.length == 0) {
        uni.showToast({
          title: "请先扫条码",
          icon: "none",
          duration: 3000,
        });
        TTSSpeech.speak({
          text: "请先扫条码",
        });
        return;
      }
      var barcodes = [];
      this.arr.forEach((item) => (barcodes += item.barcode + ","));
      let data = {
        username: this.uid,
        barcodes,
      };

      this.saveFlag = true;
      uni.request({
        url: `http://${this.url}/bService.asmx/CpzxdBarcode_bx`,
        method: "GET",
        // header: {
        // 	'content-type': 'application/x-www-form-urlencoded'
        // },
        data,
        success: (r) => {

          if (r.data.code == 0) {
            let maxLength = 2;
            let strcm = r.data.data.map((i) =>
              i.chimadetail.map((j) => j.chima)
            );
            let strsl = r.data.data.map((i) => i.chimadetail.map((j) => j.sl));
            let lengthList = [...strcm, ...strsl].flat(Infinity);
            lengthList.forEach((item) => {
              let itemLength = String(item).length;
              maxLength = Math.max(maxLength, itemLength);
            });

            this.sucBackData = r.data.data.map((i) => ({
              ...i,
              strChima: this.padStringsToMaxLength(
                i.chimadetail.map((j) => j.chima).join(","),
                maxLength
              ),
              strSl: this.padStringsToMaxLength(
                i.chimadetail.map((j) => j.sl).join(","),
                maxLength
              ),
            }));

            this.printSingleItem(0);
            this.arr = [];
            this.tm = "";
            this.bbreed = "";
            this.color = "";
            this.chima = "";
            this.sl = "";
          } else {
            uni.showToast({
              title: r.data.msg,
              icon: "none",
              duration: 3000,
            });
            TTSSpeech.speak({
              text: r.data.msg,
            });
          }
        },
        complete: (r) => {
          uni.hideLoading();
          console.log(r.statusCode != 200);
          if (r.statusCode != 200) {
            uni.showToast({
              title: "网络请求失败!",
              icon: "none",
              duration: 3000,
            });
          }
          this.saveFlag = false;
        },
      });
    },

    prepareSend: function (buff) {
      //准备发送，根据每次发送字节数来处理分包数量
      //console.log(buff)
      var that = this;
      var time = that.oneTimeData;
      var looptime = parseInt(buff.length / time);
      var lastData = parseInt(buff.length % time); //console.log(looptime + "---" + lastData)

      that.setData({
        looptime: looptime + 1,
        lastData: lastData,
        currentTime: 1,
      });
      that.Send(buff);
    },
    Send: function (buff) {
      //分包发送
      var that = this;
      var currentTime = that.currentTime;
      var loopTime = that.looptime;
      var lastData = that.lastData;
      var onTimeData = that.oneTimeData;
      var printNum = that.printerNum;
      var currentPrint = that.currentPrint;
      var buf;
      var dataView;

      if (currentTime < loopTime) {
        buf = new ArrayBuffer(onTimeData);
        dataView = new DataView(buf);

        for (var i = 0; i < onTimeData; ++i) {
          dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
        }
      } else {
        buf = new ArrayBuffer(lastData);
        dataView = new DataView(buf);

        for (var i = 0; i < lastData; ++i) {
          dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
        }
      } //console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)

      uni.writeBLECharacteristicValue({
        deviceId: that.deviceId,
        serviceId: "49535343-FE7D-4AE5-8FA9-9FAFD205E455",
        characteristicId: "49535343-8841-43F4-A8D4-ECBE34729BB3",
        value: buf,
        success: function (res) {
          if (currentPrint == printNum) {
            uni.showToast({
              title: "已打印第" + currentPrint + "张成功",
            });
          } //console.log(res)
        },
        fail: function (e) {
          uni.showToast({
            title: "打印第" + currentPrint + "张失败",
            icon: "none",
          }); //console.log(e)
        },
        complete: function () {
          currentTime++;

          if (currentTime <= loopTime) {
            that.setData({
              currentTime: currentTime,
            });
            that.Send(buff);
          } else {
            // wx.showToast({
            //   title: '已打印第' + currentPrint + '张',
            // })`
            if (currentPrint == printNum) {
              that.setData({
                looptime: 0,
                lastData: 0,
                currentTime: 1,
                isLabelSend: false,
                currentPrint: 1,
              });
            } else {
              currentPrint++;
              that.setData({
                currentPrint: currentPrint,
                currentTime: 1,
              });
              that.Send(buff);
            }
          }
        },
      });
    },
  },
};
</script>

<style>
.cell {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 20rpx 0;
}

.cell-item {
  display: flex;
  align-items: center;
  width: 50%;
}

.cell-item text {
  width: 120rpx;
}

.cell-item input {
  border: 1px solid #ccc;
  width: 60%;
}
</style>
